package com.wrt.produce.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import com.wrt.produce.dao.DataSourceMapper;
import com.wrt.produce.entity.TableDetail;
import com.wrt.produce.entity.Tables;
import com.wrt.produce.service.DataSourceDetailService;

import lombok.extern.log4j.Log4j2;

/**
 * 数据库文档服务实现类
 * 
 * @author 文瑞涛
 * @date 2021年7月13日 上午11:13:24
 */
@Service
@Log4j2
public class DataSourceDetailServiceImpl implements DataSourceDetailService {

	private static final String DEFAULT_TITLE = "数据库表设计文档";

	@Autowired
	private DataSourceMapper dataSourceMapper;

	@Override
	public List<TableDetail> getDataSourceDetail(String dbName, String tableName) {
		return dataSourceMapper.getDataDetail(dbName, tableName);
	}

	@Override
	public List<Tables> getAllDataSourceName(String tableName) {
		return dataSourceMapper.getAllDataSourceName(tableName);
	}

	@Override
	public File toWord(String dbName, List<Tables> listAll) {
		XWPFDocument document = new XWPFDocument();
		XWPFParagraph paragraphTitle = document.createParagraph();
		paragraphTitle.setAlignment(ParagraphAlignment.CENTER);
		XWPFRun runTitle = paragraphTitle.createRun();
		runTitle.setText(DEFAULT_TITLE);
		runTitle.setFontSize(24);
		int i = 0;
		for (Tables datatable : listAll) {
			// 表名
			String tableName = datatable.getTableName();
			// 表说明
			String tableComment = datatable.getTableComment();
			// 获取某张表的所有字段说明
			List<TableDetail> list = this.getDataSourceDetail(dbName, tableName);
			// 构建表说明
			String tableNameText = (i + 1) + ".表名：" + tableName + (StringUtils.isNotEmpty(tableComment) ? " [" + tableComment + "]" : StringUtils.EMPTY);
			i++;
			XWPFParagraph paragraphTable = document.createParagraph();
			XWPFRun runTable = paragraphTable.createRun();
			runTable.setText(tableNameText);
			// 表格
			XWPFTable table = document.createTable();
			table.setWidth("100%");
			// 表头
			XWPFTableRow tableRowTitle = table.getRow(0);
			createTableRowTitle(tableRowTitle);
			createDataTable(list, table);
			XWPFParagraph paragraphSpace = document.createParagraph();
			XWPFRun runSpace = paragraphSpace.createRun();
			runSpace.setText(StringUtils.EMPTY);
		}
		
		File docFile = createWordFile(dbName);
		try(FileOutputStream fos = new FileOutputStream(docFile)) {
			document.write(fos);
			return docFile;
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				document.close();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		}
		return null;
	}

	/**
	 * 创建表格标题
	 * 
	 * @param tableRowTitle
	 * 			表格首行对象
	 */
	private void createTableRowTitle(XWPFTableRow tableRowTitle) {
		setRowTitleCell(tableRowTitle.getCell(0), "序号", 0);
		setRowTitleCell(tableRowTitle.addNewTableCell(), "字段名", 1);
		setRowTitleCell(tableRowTitle.addNewTableCell(), "类型", 2);
		setRowTitleCell(tableRowTitle.addNewTableCell(), "是否为空", 3);
		setRowTitleCell(tableRowTitle.addNewTableCell(), "主键", 4);
		setRowTitleCell(tableRowTitle.addNewTableCell(), "字段说明", 5);
	}
	
	/**
	 * 设置表格标题格式及内容
	 * 
	 * @param cell
	 * 			表格单元格对象
	 * @param cellText
	 * 			单元格内容
	 * @param index
	 * 			单元格序号（第几个）
	 */
	private void setRowTitleCell(XWPFTableCell cell, String cellText, int index) {
		cell.setText(cellText);
		cell.setColor("B0C4DE");
		cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
		XWPFParagraph tableRowTitleParagraph = cell.getParagraphArray(0);
		tableRowTitleParagraph.setAlignment(ParagraphAlignment.CENTER);
		switch (index) {
		case 0:
		case 3:
			cell.setWidth("7%");
			break;
		case 1:
		case 2:
		case 4:
			cell.setWidth("20%");
			break;
		case 5:
			cell.setWidth("26%");
			break;
		default:
			break;
		}
	}

	/**
	 * 载入数据到表格内
	 * 
	 * @param list
	 * 			数据库表集合
	 * @param table
	 * 			word文件表格对象
	 */
	private void createDataTable(List<TableDetail> list, XWPFTable table) {
		int k = 0;
		for (TableDetail td : list) {
			// 获取某表每个字段的详细说明
			XWPFTableRow dataRow = table.createRow();
			dataRow.getCell(0).setText(String.valueOf(k + 1));
			dataRow.getCell(1).setText(td.getField());
			dataRow.getCell(2).setText(td.getType());
			dataRow.getCell(3).setText(td.getNull());
			dataRow.getCell(4).setText(td.getKey());
			dataRow.getCell(5).setText(td.getComment());
			k++;
		}
	}

	/**
	 * 创建word文件
	 * 
	 * @param dbName
	 * 			数据库名称
	 * @return 文件对象
	 */
	private File createWordFile(String dbName) {
		String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
		File pathFile = new File(path, "temp");
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		return new File(pathFile.getAbsolutePath(), dbName + DEFAULT_TITLE + ".docx");
	}
}
